/**
 * Created by TomSean on 2017/6/9.
 */
var OwnerEdit = function ($) {
    this.$parent = $;
    this.sysUtils = new kendoUtils();
    this.init();
    return this;
}
OwnerEdit.prototype = {
    init: function () {
        var $this = this;
        var proc = 0;
        $this.procInit(proc);
    },
    procInit: function (proc) {
        var $this = this;
        if (0 == proc) {
            // 加载权限组
            JsonpAjax(baseApiPath + 'crAccessPermissionInfo/selectAll', null, 'GET', 'json', null, function (res) {
                if (undefined == res || '' == res || res.data.length < 1) {
                    $('#permission_group').html('暂未添加任何权限组');
                } else {
                    var ul = $('<ul></ul>');
                    var permissionCodes = ownerManager.entity == undefined ? '' : ownerManager.entity.permissionCodes;
                    for (var i = 0; i < res.data.length; i++) {
                        var li = $('<li></li>');
                        var a = $('<a data-value="' + res.data[i].id + '">' + res.data[i].accessName + '</a>')
                        a.bind('click', function (event) {
                            var checked = false;

                            if ($(this).hasClass('choice')) {
                                $(this).removeClass('choice');
                                checked = false;
                            } else {
                                $(this).addClass('choice');
                                checked = true;
                            }
                            JsonpAjax(baseApiPath + 'access_permission/get/' + $(this).attr('data-value'), '', 'json', function (res) {
                                if (undefined == res || '' == res || res.data.length < 1) {
                                    return;
                                }
                                var codes = res.data.accessChannelCode;
                                var codeArray = codes.split(',');
                                for (var i = 0; i < codeArray.length; i++) {
                                    var node = $this.pointTree.getNodeByParam('code', codeArray[i], null);
                                    var count = $this.cacheTree.get(codeArray[i]);
                                    if (isEmpty(count)) {
                                        count = 0;
                                    }
                                    ;
                                    if (checked) {
                                        count++;
                                    } else {
                                        count--;
                                    }
                                    $this.cacheTree.put(codeArray[i], count);
                                    if (count <= 0) {
                                        $this.pointTree.checkNode(node, false, true);
                                    } else {
                                        $this.pointTree.checkNode(node, true, true);
                                    }
                                }
                            }, true);
                        });
                        li.append(a);
                        if (permissionCodes.indexOf(res.data[i].id) != -1) {
                            ul.prepend(li);
                        } else {
                            ul.append(li);
                        }
                    }
                    $this.$parent.find('#permission_group').append(ul);
                }
                $this.procInit(++proc);
            });
        } else if (1 == proc) {
            // 加载权限树节点
            JsonpAjax(baseApiPath + 'OrganizationInfo/selectAllOrganization', null, 'GET', 'json', null, function (res) {
                if (undefined == res || '' == res || res.data.length < 1) {
                    $('#permission_point').html('暂未添加任何通道');
                    return;
                }
                var setting = {
                    view: {
                        showLine: true,
                        selectedMulti: false,
                        dblClickExpand: false,
                        showIcon: false
                    },
                    data: {
                        simpleData: {
                            enable: true,
                            idKey: "code",
                            pIdKey: "pid",
                            rootPId: ""
                        }
                    },
                    check: {
                        enable: true,
                        autoCheckTrigger: true,
                        chkStyle: "checkbox",
                        chkboxType: {"Y": "s", "N": "s"}
                    }
                };
                $this.pointTree = $.fn.zTree.init($('#permission_point_ul'), setting, res.data);
                $this.pointTree.setting.check.chkboxType = {'Y': 's', 'N': 's'};

                $this.cacheTree = new Map();
                $this.pointTree.expandAll(true);
                $this.procInit(++proc);
            }, true);
        } else if (2 == proc) {
            // 加载组织结构
            JsonpAjax(baseApiPath + 'pbaOwnerOrganization/selectAllTree', null, 'GET', 'json', null, function (res) {
                var setting = {
                    view: {
                        showLine: true,
                        selectedMulti: false,
                        dblClickExpand: false,
                        showIcon: false
                    },
                    data: {
                        key: {
                            children: 'items',
                            name: 'fullName',
                            title: 'fullName'
                        }
                    },
                    check: {
                        enable: false,
                        autoCheckTrigger: true,
                        chkStyle: "checkbox",
                        chkboxType: {"Y": "s", "N": "s"}
                    }
                };
                if (!isEmpty(ownerManager.entity) && !isEmpty(ownerManager.entity.organization)) {
                    $('[data-bind="organization-tree"]').val(ownerManager.entity.organization.organizationCode);
                }
                var organizationTree = $('#organization-tree').lonixFloat({
                    source: res.data,
                    setting: setting,
                    searchField: 'fullName',
                    target: $('[data-bind="organization-tree"]'),
                    primary: function (nodes) {
                        var node = nodes[0];
                        var codes = node.id;
                        var names = '';
                        while (true) {
                            if (names == '') {
                                names = node.fullName;
                            } else {
                                names = node.fullName + ' > ' + names;
                            }
                            if (!node.getParentNode() || node.getParentNode().level == 0) {
                                break;
                            }
                            node = node.getParentNode();
                        }
                        $('[data-bind="organization-tree"]').val(names);
                        $('#organization-id').val(codes);
                        $('#organization-tree').fadeUp();
                    }
                });
                $this.organizationTree = organizationTree;
                $this.procInit(++proc);
            }, true);
        } else if (3 == proc) {
            // 添加车辆事件
            $this.$parent.find('.vehicle_div.add').bind('click', function (event) {
                var vehicle_div = '<div class="vehicle_div edit" data-new>';
                vehicle_div += '<a onclick="removeVehicleDiv(this)" class="delete_vehicle" style="display: block;"></a>';
                vehicle_div += '<label class="vehicle_no"><input type="text" placeholder="车牌号" onkeydown="ownerEdit.checkVehicleNoInput(event)"  /></label>';
                vehicle_div += '<table>';
                vehicle_div += '    <tr>';
                vehicle_div += '        <td>车辆品牌：</td>';
                vehicle_div += '        <td class="vehicle_category"><input type="text" /></td>';
                vehicle_div += '    </tr>';
                vehicle_div += '    <tr>';
                vehicle_div += '        <td>车牌颜色：</td>';
                vehicle_div += '        <td class="vehicle_logo"><input type="text" /></td>';
                vehicle_div += '    </tr>';
                vehicle_div += '    <tr>';
                vehicle_div += '        <td>车体类型：</td>';
                vehicle_div += '        <td class="vehicle_type">' + $this.getVehicleTypeSelect() + '</td>';
                vehicle_div += '    </tr>';
                vehicle_div += '    <tr>';
                vehicle_div += '        <td>车体颜色：</td>';
                vehicle_div += '        <td class="vehicle_color"><input type="text" /></td>';
                vehicle_div += '    </tr>';
                vehicle_div += '</table>';
                vehicle_div += '</div>';
                $(this).before(vehicle_div);
            });
            $this.procInit(++proc);
        } else if (4 == proc) {
            this.initParam();
            this.deployData(ownerManager.entity);
            this.deployVehicle(ownerManager.vehicleinfo);
        }
    },

    // 校验车辆信息
    validateVehicle: function () {
        var $this = this;
        var t = true;
        if ($this.$parent.find('.vehicle_div').not('.add').length == 0) {
            notification({'title': '错误', 'message': '请先录入车辆！'}, 'error');
            t = false;
            return t;
        } else {
            t = true;
        }
        $this.$parent.find('.vehicle_div').not('.add').each(function (inx, itm) {
            var input_val = '' + $(itm).find('label.vehicle_no input').val();
            input_val = input_val.toLowerCase();
            if (isEmpty(input_val) || isEmpty(input_val.trim())) {
                t = false;
                return false;
            }
            if (!(/^[a-zA-Z\d\u4e00-\u9fa5]+$/.test(input_val))) {
                notification({'title': '错误', 'message': '车牌[' + input_val + ']中包含了不可描述的字符！请修改正确'}, 'error');
                t = false;
                return false;
            }
            if (input_val.indexOf('i') != -1) {
                notification({'title': '错误', 'message': '车牌[' + input_val + ']中包含了不合规字符 "i" 请检查后修改正确'}, 'error');
                t = false;
                return false;
            }
            if (input_val.indexOf('o') != -1 && input_val.indexOf('警') == -1) {
                notification({'title': '错误', 'message': '车牌[' + input_val + ']非警牌，不能包含字符 "o" 请检查后修改正确'}, 'error');
                t = false;
                return false;
            }
            if ('京津冀晋蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼川贵云渝藏陕甘青宁新'.indexOf(input_val.charAt(0)) == -1) {
                notification({'title': '错误', 'message': '车牌省份不正确！'}, 'error');
                t = false;
                return false;
            }
            if (input_val.length < 7) {
                notification({'title': '错误', 'message': '车牌[' + input_val + ']有误！长度小于标准车牌长度'}, 'error');
                t = false;
                return false;
            }
            if (input_val.length > 8) {
                notification({'title': '错误', 'message': '车牌[' + input_val + ']有误！长度超出标准车牌长度'}, 'error');
                t = false;
                return false;
            }
        });
        return t;
    },

    // 部署值到表单
    deployData: function (data) {
        var $this = this;
        if (!isEmpty(data)) {
            $this.$parent.find('[name="ownerCode"]').val(data.ownerCode);
            $this.$parent.find('[name="ownerName"]').val(data.ownerName);
            $this.$parent.find('[name="ownerPhone"]').val(data.ownerPhone);
            $this.$parent.find('[name="ownerAddress"]').val(data.ownerAddress);
            if (!isEmpty(data.organization)) {
                $this.$parent.find('[name="organization_id"]').val(data.organization.organizationCode);
                var node = $this.organizationTree.ztree.getNodeByParam('id', data.organization.organizationCode);
                var names = '';
                while (true) {
                    if (names == '') {
                        names = node.fullName;
                    } else {
                        names = node.fullName + ' > ' + names;
                    }
                    if (!node.getParentNode() || node.getParentNode().level == 0) {
                        break;
                    }
                    node = node.getParentNode();
                }
                $this.$parent.find('#info-tree');
                $this.$parent.find('#organization_text').val(names);
            }
            $this.$parent.find('[name="remark"]').val(data.remark);
            var permissionCodes = data.permissionCodes;
            if (!isEmpty(permissionCodes)) {
                var permissionArray = permissionCodes.split(",");
                for (var i = 0; i < permissionArray.length; i++) {
                    $this.$parent.find('a[data-value="' + permissionArray[i] + '"]').click();
                }
            }
        }
    },

    // 部署值到车辆
    deployVehicle: function (data) {
        var $this = this;
        if (!isEmpty(data)) {
            for (var i = 0; i < data.length; i++) {
                $this.addVehicle(data[i].vehicleNo, data[i].vehicleCategory, data[i].vehicleLogo, Utils.getModelNameByParentKey(BASIS.VEHICLE_TYPE.ROOT, data[i].vehicleType), data[i].vehicleType, data[i].vehicleColor);
            }
        }
    },

    addVehicle: function (no, category, logo, type_name, type_value, color) {
        var vehicle_div = '';
        vehicle_div += '<div class="vehicle_div">';
        vehicle_div += '<a onclick="removeVehicleDiv(this)" class="delete_vehicle"></a>';
        vehicle_div += '    <label class="vehicle_no"><input type="text" placeholder="车牌号" value="' + no + '" onkeydown="ownerEdit.checkVehicleNoInput(event)" /></label>';
        vehicle_div += '    <table>';
        vehicle_div += '        <tr>';
        vehicle_div += '            <td>车辆品牌：</td>';
        vehicle_div += '            <td class="vehicle_category"><input type="text" value="' + category + '" /></td>';
        vehicle_div += '        </tr>';
        vehicle_div += '        <tr>';
        vehicle_div += '            <td>车牌颜色：</td>';
        vehicle_div += '            <td class="vehicle_logo"><input type="text" value="' + logo + '" /></td>';
        vehicle_div += '        </tr>';
        vehicle_div += '        <tr>';
        vehicle_div += '            <td>车体类型：</td>';
        vehicle_div += '            <td class="vehicle_type" data-value="' + type_value + '">' + this.getVehicleTypeSelect(type_name) + '</td>';
        vehicle_div += '        </tr>';
        vehicle_div += '        <tr>';
        vehicle_div += '            <td>车体颜色：</td>';
        vehicle_div += '            <td class="vehicle_color"><input type="text" value="' + color + '" /></td>';
        vehicle_div += '        </tr>';
        vehicle_div += '    </table>';
        vehicle_div += '</div>';
        this.$parent.find('.vehicle_div.add').before(vehicle_div);
    },

    checkVehicleNoInput: function (event) {
        if (event.keyCode == 32) {
            event.cancelBubble = true;
            event.returnValue = false;
            return false;
        }
    },

    // 初始化参数
    initParam: function () {
        var typeArray = Utils.getModelArrayByParentModelKey(BASIS.VEHICLE_TYPE.ROOT);
        this.vehicleTypes = typeArray;
    },

    // 获取车辆类型下拉
    getVehicleTypeSelect: function (opt) {
        var html = '<select>';
        for (var i = 0; i < this.vehicleTypes.length; i++) {
            var selected = this.vehicleTypes[i].modelName == opt ? 'selected' : '';
            html += '<option ' + selected + ' value="' + this.vehicleTypes[i].modelValue + '">' + this.vehicleTypes[i].modelName + '</option>';
        }
        html += '</select>';
        return html;
    },

    // 通过车辆类型的value获取text
    getVehicleTypeText: function (value) {
        for (var i = 0; i < this.vehicleTypes.length; i++) {
            if (this.vehicleTypes[i].modelValue == value) {
                return this.vehicleTypes[i].modelName;
            }
        }
    },

    // 保存车主信息
    saveOwnerInfo: function () {
        if (!this.validateVehicle()) {
            // notification({title : '错误', message : '车牌号信息有误，请仔细核对'}, 'error')
            return;
        }
        var entity = {};
        var ownerInfo = {};
        ownerInfo['ownerName'] = this.$parent.find('input[name="ownerName"]').val();
        ownerInfo['ownerPhone'] = this.$parent.find('input[name="ownerPhone"]').val();
        if (isEmpty(ownerInfo['ownerName'])) {
            notification({'title': '错误', 'message': '用户姓名不能为空！'}, 'error');
            return;
        }
        if (!(/^[\u4e00-\u9fa5\w\-]*$/.test(ownerInfo['ownerName']))) {
            notification({'title': '错误', 'message': '姓名只能为汉字大小写因为字母、数字、-、_'}, 'error');
            return;
        }
        if (!isEmpty(ownerInfo['ownerPhone']) && !(/^1[34578]\d{9}$/.test(ownerInfo['ownerPhone']))) {
            notification({'title': '错误', 'message': '手机号码有误，请重填'}, 'error');
            return;
        }
        ownerInfo['ownerAddress'] = this.$parent.find('input[name="ownerAddress"]').val();
        ownerInfo['remark'] = this.$parent.find('textarea[name="remark"]').val();
        entity['ownerInfo'] = ownerInfo;
        entity['organization'] = this.$parent.find('input[name="organization_id"]').val();

        entity['permissionGroup'] = [];
        this.$parent.find('#permission_group a[class="choice"]').each(function (inx, itm) {
            entity['permissionGroup'].push($(itm).attr('data-value'));
        });
        if (entity['permissionGroup'].length == 0) {
            notification({'title': '错误', 'message': '必须选择一个通行权限组'}, 'error');
            return;
        }
        entity['vehicleArray'] = [];
        var tempVehicleNo = '';
        var flagStop = false;
        this.$parent.find('#owner_vehicles .vehicle_div').not('.add').each(function (inx, itm) {
            var vehicle = {};
            vehicle['vehicleNo'] = $(itm).find('.vehicle_no input').val();
            if (tempVehicleNo.indexOf('[' + vehicle['vehicleNo'] + ']') != -1) {
                notification({'title': '错误', 'message': '车牌重复入录！！！' + '[' + vehicle['vehicleNo'] + ']'}, 'error');
                flagStop = true;
                return false;
            }
            tempVehicleNo += '[' + vehicle['vehicleNo'] + ']';
            vehicle['vehicleCategory'] = $(itm).find('.vehicle_category input').val();
            vehicle['vehicleLogo'] = $(itm).find('.vehicle_logo input').val();
            vehicle['vehicleType'] = $(itm).find('.vehicle_type select').val();
            vehicle['vehicleColor'] = $(itm).find('.vehicle_color input').val();
            entity['vehicleArray'].push(vehicle);
        });
        if (flagStop) {
            return;
        }
        let url = baseApiPath + 'owner_info/save?code=' + this.$parent.find('[name="ownerCode"]').val();
        JsonpAjax(url, JSON.stringify(entity), function (res) {
            $('#' + ownerManager.editDiv).data('kendoWindow').close();
            ownerManager.findData();
        });
    },

    // 获取车辆信息
    getVehicleInfo: function () {

    }
};